package com.db.service.bank;

import com.db.domain.bank.Bank;
import com.db.domain.bank.Client;
import com.db.exceptions.BankException;
import com.db.exceptions.ClientExistsException;

import java.io.*;
import java.util.Arrays;

public class BankService {
    private String fileName = "test.ser";

    public void addClient(Bank bank, Client client) throws BankException {
        if (Arrays.asList(bank.getClients()).contains(client)) {
            throw new ClientExistsException(client.getName());
        }
        bank.addClient(client);
        saveBank(bank);
    }

    public void printMaximumAmountToWithdraw(Bank bank) {
        for(Client client: bank.getClients()) {
            System.out.println(client.getName() + " : " + client.getAccount().getBalance());
        }
    }

    public void saveBank(Bank bank) {
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File(fileName)))) {
            objectOutputStream.writeObject(bank);
        } catch (IOException e) {
           System.err.println("Can't save bank");
            e.printStackTrace();
        }
    }

    public Bank readBank(String path) {
        fileName = path;
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(path)))) {
            return (Bank) ois.readObject();
        } catch (IOException e) {
            System.err.println("Can't read file with bank. Please, check path.");
        } catch (ClassNotFoundException e) {
            System.err.println("Error data in file. Please, try another file.");
        }
        return null;
    }
}
